<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate(1)"> 查询设计器 </a-button>
        <a-button type="primary" @click="handleCreate(2)"> 自由查询 </a-button>
        <a-button type="primary" @click="deleteBatch"> 删除 </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              onClick: handleEdit.bind(null, record),
              tooltip: '设计',
            },
            {
              icon: 'ant-design:file-protect-outlined',
              onClick: handleAuth.bind(null, record),
              tooltip: '授权',
            },
            {
              icon: 'ant-design:file-search-outlined',
              onClick: handleSearch.bind(null, record),
              tooltip: '查询',
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: '删除',
              popConfirm: {
                title: '是否确认删除',
                placement: 'leftBottom',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <SearchDesignerDrawer @register="registerDrawer" @success="handleSuccess" />
    <SelectAll @register="registerModal" @success="handleModalSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useDrawer } from '/@/components/Drawer';
  import SearchDesignerDrawer from './searchDesignerDrawer.vue';
  import { columns, searchFormSchema } from './searchDesigner.data';
  import {
    getQueryList,
    getQueryDel,
    getQueryGetQueryPrivilege,
  } from '/@/api/reportForms/reportForms';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useGo } from '/@/hooks/web/usePage';
  import { useModal } from '/@/components/Modal';
  import { getQuerySetQueryPrivilege } from '/@/api/reportForms/reportForms';
  import { SelectAll } from '/@/components/CustomComp';

  export default defineComponent({
    name: 'SearchDesigner',
    components: { BasicTable, SearchDesignerDrawer, TableAction, SelectAll },
    setup() {
      const go = useGo();
      const { createMessage, createConfirm } = useMessage();
      const [registerModal, { openModal }] = useModal();
      const [registerDrawer, { openDrawer }] = useDrawer();
      const [registerTable, { reload, getSelectRowKeys, setLoading }] = useTable({
        title: '查询设计',
        api: getQueryList,
        columns,
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema,
          autoSubmitOnEnter: true,
        },
        searchInfo: {
          op: 'search',
        }, //额外的参数
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        indexColumnProps: { width: 50 },
        showIndexColumn: true,
        actionColumn: {
          width: 140,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
      });

      function handleCreate(type) {
        if (type == 1) {
          go('/searchDesignerView');
        } else if (type == 2) {
          go('/searchDesignerFree');
        }
        // openDrawer(true, {
        //   isUpdate: false,
        // });
      }

      function handleEdit(record: Recordable) {
        if (record.type == '普通查询') {
          go({
            path: '/searchDesignerView',
            query: {
              id: record.id,
            },
          });
        } else if (record.type == '自由查询') {
          go({
            path: '/searchDesignerFree',
            query: {
              id: record.id,
            },
          });
        }
      }

      function handleDelete(record: Recordable) {
        deleteById(record.id);
      }

      function handleSuccess() {
        reload();
      }

      //批量删除
      const deleteBatch = async () => {
        let keys = getSelectRowKeys();
        if (keys.length == 0) {
          createMessage.warning('请选择需要删除的数据');
          return;
        }
        createConfirm({
          iconType: 'warning',
          title: '确定删除吗？',
          onOk: async () => {
            deleteById(keys.join(','));
          },
        });
      };

      const deleteById = async (keys) => {
        try {
          await getQueryDel({
            ids: keys,
          });
          handleSuccess();
          createMessage.success('操作成功');
        } catch (error) {}
      };

      const currentRecord = ref<Recordable>({});
      //授权
      const handleAuth = async (record) => {
        currentRecord.value = record;
        const data = await getQueryGetQueryPrivilege({ id: record.id });
        let hadUsers = [];
        if (data && data.length) {
          hadUsers = data.map((item) => {
            return {
              key: item.value,
              name: item.value,
              title: item.label,
              realName: item.label,
              newTitle: item.label,
              privType:
                item.type == 'role'
                  ? '2'
                  : item.type == 'user'
                  ? '0'
                  : item.type == 'dept'
                  ? '1'
                  : '',
            };
          });
        }
        openModal(true, {
          isUpdate: false,
          tabKeys: ['1', '2', '4'],
          users: hadUsers,
        });
      };
      const handleModalSuccess = async (users) => {
        try {
          console.log('users', users);
          if (users && users.length > 0) {
            let dataList: Recordable[] = [];
            users.forEach((item) => {
              let name = item.key;
              if (item.privType == 3) {
                name = item.code;
              }
              dataList.push({
                code: name,
                name: item.title,
                kind: item.privType,
              });
            });
            const formData = {
              id: currentRecord.value.id,
              users: JSON.stringify(dataList),
            };
            console.log('formData', formData);
            setLoading(true);
            await getQuerySetQueryPrivilege(formData);
            createMessage.success('操作成功');
          }
        } catch (error) {
          console.log(error);
        } finally {
          setLoading(false);
        }
      };
      //查询
      const handleSearch = (record) => {
        if (record.type === '自由查询') {
          go({
            path: '/searchTable',
            query: {
              id: record.id,
              title: record.name,
              cacheName: `searchTable${record.id}`,
            },
          });
        } else {
          go({
            path: '/searchTableNormal',
            query: {
              id: record.id,
              title: record.name,
              cacheName: `searchTableNormal${record.id}`,
            },
          });
        }
      };
      return {
        registerTable,
        registerDrawer,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        deleteBatch,
        handleAuth,
        handleSearch,
        registerModal,
        handleModalSuccess,
      };
    },
  });
</script>
